package cn.b504.qpcr.controller;

import cn.b504.qpcr.entity.AjaxResult;
import cn.b504.qpcr.entity.ErrorCode;
import cn.b504.qpcr.entity.data.manager.DM;
import cn.b504.qpcr.interfaces.data.manager.DataManager;
import cn.b504.qpcr.utils.FileUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * download files from data manager
 *
 * @author ssc
 * @apiNote update: 2021-04-19 19:50 by ssc
 * @create 2019-04-18 13:42
 */
@RestController
@RequestMapping("dataManager")
public class DataManagerController {
  private final DataManager dataManager;

  public DataManagerController(DataManager dataManager) {
    this.dataManager = dataManager;
  }

  @RequestMapping("refresh")
  public AjaxResult refresh(@RequestBody String ip) {
    if (ip == null) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "ip 为空");
    }
    return AjaxResult.ok(dataManager.getWorkspaces(ip));
  }

  @RequestMapping("download")
  public AjaxResult download(@RequestBody DM dm) {
    if (dm == null) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "请求参数错误");
    }
    return AjaxResult.ok(dataManager.getResult(dm));
  }

  @RequestMapping("uploadAZD")
  public AjaxResult uploadAZD(MultipartFile file) {
    File fileAZD = null;
    try {
      fileAZD = File.createTempFile("tmp", null);
      file.transferTo(fileAZD);
    } catch (IOException e) {
      e.printStackTrace();
      if (fileAZD != null) {
        FileUtils.deleteFile(fileAZD);
      }
      return AjaxResult.error(ErrorCode.FILE_UPLOAD_FAIL, file.getOriginalFilename() + " 上传失败");
    }
    return AjaxResult.ok(dataManager.getResult(fileAZD.getAbsolutePath()));
  }
}
